package com.dong8.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dong8.R;
import com.dong8.resp.RespGymDetail;
import com.dong8.sys.Constants;
import com.dong8.sys.MyApp;
import com.dong8.type.Gym;
import com.dong8.type.GymImg;
import com.dong8.util.ImageLoaderHelper;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.PreferencesUtils;
import com.dong8.util.TLog;
import com.dong8.util.ToastUtil;
import com.dong8.util.Utils;
import com.loopj.android.http.RequestParams;

@SuppressLint("HandlerLeak")
public class GymDetailHeadActivity extends Activity implements OnClickListener {
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews = new ArrayList<ImageView>();
	private ImageView ivPlayerFavorite;
	Gym mGym;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gym_detail);
		
		findViewById(R.id.titleRight).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				startActivity(new Intent(GymDetailHeadActivity.this, RecommendGymActivity.class));
			}
		});

		mGym = ((MyApp)getApplicationContext()).mCurrentGym;
		((TextView)findViewById(R.id.tv_title)).setText(mGym.clubName);

		((TextView) findViewById(R.id.name)).setText(" " + mGym.address);
		((TextView) findViewById(R.id.time)).setText(" " + mGym.workTime);

		ivPlayerFavorite = (ImageView) findViewById(R.id.ivPlayerFavorite);
		ivPlayerFavorite.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				addFavorite(v);
				String json=JSON.toJSONString(mGym);
				changeFavoriteIcon(String.valueOf(mGym.id),json);
			}
		});

		findViewById(R.id.addr).setOnClickListener(this);
		findViewById(R.id.tel).setOnClickListener(this);
		findViewById(R.id.detail).setOnClickListener(this);
		findViewById(R.id.comment).setOnClickListener(this);
		
		getData(true);
		showFavorite(String.valueOf(mGym.id));
	}
	
	private class MyPageChangeListener implements OnPageChangeListener {
		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	public void showDialog(String title, String text) 
	{
		final Dialog dialog = new Dialog(this,R.style.dialog);
		dialog.setContentView(R.layout.dialog); 
		dialog.setCancelable(true);
		
		((Button)dialog.findViewById(R.id.confirm)).setText("拨打电话");
		dialog.findViewById(R.id.confirm).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				dialog.dismiss();
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mGym.phone));
				startActivity(intent);
			}
		});
		dialog.findViewById(R.id.cancel).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				dialog.dismiss();
			}
		});
		((TextView)dialog.findViewById(R.id.msg)).setText(text);
		dialog.show();
	}
	
	@Override
	public void onClick(View arg0) 
	{
		switch (arg0.getId()) {
		case R.id.comment:
			startActivity(new Intent(this, GymCommentsActivity.class));
			break;

		case R.id.addr: 
		{
			Intent intent = new Intent(this, MapViewActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("gym", mGym);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		}

		case R.id.tel: 
			showDialog("","是否拨打场馆电话: " + mGym.phone);
			break;

		case R.id.detail: {
			Intent intent = new Intent(this, GymInstructActivity.class);
			intent.putExtra("desc", mGym.description);
			intent.putExtra("title", mGym.clubName);
			startActivity(intent);
			break;
		}
		}
	}

	private void getData(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				super.onSuccess(response);
//				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();

				TLog.i("hansen", "=======response==" + response);
				RespGymDetail ruser = JSON.parseObject(response,
						RespGymDetail.class);
				if (ruser.code == 0) {
					List<GymImg> img = ruser.picList;

					int count = img.size();
					for (int i = 0; i < count; i++) {
						ImageView imageView = new ImageView(GymDetailHeadActivity.this);
						imageView.setId(10000 + i);
						imageView.setBackgroundColor(Color.LTGRAY);
						imageView.setScaleType(ScaleType.CENTER_CROP);
						ImageLoaderHelper.displayImage(R.drawable.default_img_big,imageView, img.get(i).url);
						imageViews.add(imageView);
					}
					
					if(count == 0)
					{
						ImageView imageView = new ImageView(GymDetailHeadActivity.this);
						imageView.setBackgroundColor(Color.LTGRAY);
						imageView.setScaleType(ScaleType.CENTER_CROP);
						imageView.setImageResource(R.drawable.default_img_big);
						imageViews.add(imageView);
					}

					viewPager = (ViewPager) findViewById(R.id.vp);
					viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
					viewPager.setOnPageChangeListener(new MyPageChangeListener());
					
					final Handler handle = new Handler()
					{
						public void handleMessage(Message msg)
						{
							int pos = viewPager.getCurrentItem();
							
							if(pos < imageViews.size() - 1) viewPager.setCurrentItem(pos + 1);
							else viewPager.setCurrentItem(0);
						}
					};
					
					new Timer().schedule(new TimerTask()
					{
						@Override
						public void run() 
						{
							handle.sendEmptyMessage(0);
						}
					}, 5000, 5000);
				}
				else 
				{
				}
			}

			public void onFailure(Throwable ble) {
			}
		};

		RequestParams params = new RequestParams();
		params.put("id", mGym.id);
		MgqRestClient.get(Constants.CLUB_DETAIL, params, loginHandler);
	}

	// ---------
	/**
	 * 添加收藏
	 */
	@SuppressWarnings("unused")
	private void addFavorite(final View clickedView) {
//		static final public String ID_Favorite_LIST="Favorite_LIST";
//		static final public String ID_Favorite="FID-";
		
	
	}
	
	
	private void showFavorite(String clubId){
		String result =findFavorite(clubId);
		if(result ==null){
			ivPlayerFavorite.setImageResource(R.drawable.player_favorite_normal); 
		}else{
			ivPlayerFavorite.setImageResource(R.drawable.player_favorite_pressed); 
		}
	}

	/**
	 * 查找收藏信息
	 */
	private String findFavorite(String clubId) {
		String club=PreferencesUtils.getString(GymDetailHeadActivity.this, Constants.ID_Favorite+clubId);

		return club;
	}
	
	public void saveFavorite(String clubId,String json){
		
		String idList=PreferencesUtils.getString(GymDetailHeadActivity.this, Constants.ID_Favorite_LIST);
		idList=idList+","+clubId;
		PreferencesUtils.putString(GymDetailHeadActivity.this, Constants.ID_Favorite_LIST, idList);
		PreferencesUtils.putString(GymDetailHeadActivity.this, Constants.ID_Favorite+clubId, json);
		
		ivPlayerFavorite.setImageResource(R.drawable.player_favorite_pressed); 
		ToastUtil.showToastWithOkPic("  场馆收藏成功!  ");
	}
	
	
	
	public void removeFavorite(String clubId){
		String idList=PreferencesUtils.getString(GymDetailHeadActivity.this, Constants.ID_Favorite_LIST);
		String result=idList.replace(","+clubId, "");
		PreferencesUtils.putString(GymDetailHeadActivity.this, Constants.ID_Favorite_LIST, result);
		
		PreferencesUtils.putString(GymDetailHeadActivity.this, Constants.ID_Favorite+clubId, null);
		
		ivPlayerFavorite.setImageResource(R.drawable.player_favorite_normal); 
	}

	/**
	 * 更改收藏按钮图标
	 * 
	 * @param isFavorite  1表示已收藏、0表示未收藏
	 */
	private void changeFavoriteIcon(String clubId,String  json ) {
		String result =findFavorite(clubId);
		if(result ==null){
			saveFavorite(clubId,json);
		}else{
			removeFavorite(clubId);
		}
	}

	@Override
	public void onBackPressed() {
		this.getParent().onBackPressed();
	}
}
